<?php

App::uses('AppController', 'Controller');

/**
 * Products Controller
 *
 * @property Product $Product
 * @property PaginatorComponent $Paginator
 */
class ProductsController extends AppController {

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator');

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->Product->recursive = 0;
        $this->set('products', $this->Paginator->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
        $this->set('product', $this->Product->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->Product->create();
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('The product has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        }
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('The product has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
            $this->request->data = $this->Product->find('first', $options);
        }
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->Product->id = $id;
        if (!$this->Product->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Product->delete()) {
            $this->Session->setFlash(__('The product has been deleted.'));
        } else {
            $this->Session->setFlash(__('The product could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

    public function admin_index() {
         if ($this->request->is('post')) {
            $text = $this->request->data['search_text'];
            $this->Paginator->settings=array(
                'conditions'=>array('OR'=>array('Product.product_name LIKE'=>"%$text%",'TypeProduct.type_name LIKE'=>"%$text%")),
                'order'=>array('Product.product_name'),
                'limit'=>5
            );
        }
        else{
            $this->Paginator->settings=array(
                'order'=>array('Product.product_name'),
                'limit'=>5
            );
        }
        $this->set('products', $this->Paginator->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function detail($id = null) {
        $title_for_layout="Chi tiết sản phẩm-Shop thời trang nam nữ";
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
        $product = $this->Product->find('first', $options);
        $type='';
        if(!empty($product))
        {
            $type=$product['Product']['type_fashion'];
            $this->set(compact('type'));
        }
        $refProduct=array();
        if(!empty($product))
        {
            $product_type= $product['TypeProduct']['id'];
            $this->Paginator->settings=array('conditions'=>array('Product.type_product_id'=>$product_type,'Product.id !='=>$id,'type_fashion'=>$type),'limit'=>8,'recursive'=>-1);
            $refProduct = $this->Paginator->paginate('Product');
        }
        $this->set(compact('product','refProduct','title_for_layout'));
    }

    /**
     * add method
     *
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            $this->Product->create();
            $files = $this->request->data['Product']['image'];
            move_uploaded_file($files['tmp_name'], WWW_ROOT . '/img/frontend/product/' . $files['name']);
            $this->request->data['Product']['create_date'] = date("Y-m-d");
            $this->request->data['Product']['create_person'] = $this->Session->read("userName");
            $this->request->data['Product']['image'] = $this->webroot . "img/frontend/product/" . $files['name'];
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('Sửa thành công '), 'backend/green', array('redirect' => ''));
                return $this->redirect(array('action' => 'admin_index'));
            } else {
                $this->Session->setFlash(__('Could not be saved. Please, try again.'));
            }
        } else {
            $productCode = $this->Product->find('first',array('fields'=>array('Max(Product.id) as maxid')));
            $this->loadModel('TypeProduct');
            $typeProduct = $this->TypeProduct->find('list', array('fields' => array('id', 'type_name')));
            $this->set(compact('typeProduct','productCode'));
        }
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            $files = $this->request->data['Product']['image'];
            if($files['name'])
            {    
                unlink('http://'.$_SERVER['SERVER_NAME'].$this->request->data['old_image']);
                move_uploaded_file($files['tmp_name'], WWW_ROOT . '/img/frontend/product/' . $files['name']);
                $this->request->data['Product']['image'] = $this->webroot . "img/frontend/product/" . $files['name'];
            }
            else{
                $this->request->data['Product']['image']=$this->request->data['old_image'];
            }
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('Thêm thành công '), 'backend/green', array('redirect' => ''));
                return $this->redirect(array('action' => 'admin_index'));
            } else {
                $this->Session->setFlash(__('Could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
            $this->request->data = $this->Product->find('first', $options);
            $this->loadModel('TypeProduct');
            $typeProduct = $this->TypeProduct->find('list', array('fields' => array('id', 'type_name')));
            $this->set(compact('typeProduct'));
        }
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        $this->Product->id = $id;
        if (!$this->Product->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }
        $this->request->onlyAllow('get', 'admin_delete');

        if ($this->Product->delete()) {
            $this->Session->setFlash(__('Xóa thành công'), 'backend/green', array('redirect' => ''));
        } else {
            $this->Session->setFlash(__('Lỗi xóa dữ liệu'), 'backend/red', array('redirect' => ''));
        }
        return $this->redirect(array('action' => 'admin_index'));
    }
    public function getHotProduct()
    {
        $hots = $this->Product->find('all',array('conditions'=>array('Product.type'=>2),'recursive'=>-1));
        return $hots;
        
    }
    public function getNewProduct()
    {
        $hots = $this->Product->find('all',array('conditions'=>array('Product.type'=>1),'recursive'=>-1));
        return $hots;
        
    }
    public function type_fashion($type=null)
    {
        if($type==1)
        {
            $title_for_layout="Thời trang nam-Shop thời trang nam nữ";
        }
        else if($type==2)
        {
            $title_for_layout="Thời trang nữ-Shop thời trang nam nữ";
        }
        else{
            $title_for_layout="Shop thời trang nam nữ";
        }
        $this->set(compact('type','title_for_layout'));
    }
    public function type_product($type_product=null)
    {
        $title_for_layout="Danh mục sản phẩm-Shop thời trang nam nữ";
        $order = array('Product.price'=>'DESC');
        $idOrder=1;
        if(isset($_POST['order']))
        {
            $idOrder=$_POST['order'];
            if($idOrder==2)
            {
                $order = array('Product.price'=>'ASC');
            }
        }
        $this->loadModel('TypeProduct');
        $typeProducts = $this->TypeProduct->find('first',array('conditions'=>array('TypeProduct.id'=>$type_product),'recursive'=>-1));
        if(!empty($typeProducts))
        {
            $type=$typeProducts['TypeProduct']['type_fashion'];
            $this->set(compact('type'));
        }
        $this->Paginator->settings=array(
            'conditions'=>array('Product.type_product_id'=>$type_product),
            'order'=> $order,
            'limit'=>8,
            
            'recursive'=>-1
        );
        $products=$this->Paginator->paginate('Product');
        $this->set(compact('type_product','typeProducts','products','idOrder','title_for_layout'));
    }
    public function search()
    {
        $products =array();
        if($this->request->is('post'))
        {
            $key = $this->request->data['key'];
            if(!empty($key))
            {
                $this->Paginator->settings=array('conditions'=>array(
                                            'OR'=>array('Product.product_name LIKE'=>'%'.$key.'%',
                                                'Product.price LIKE'=>'%'.$key.'%',
                                                'Product.product_code LIKE'=>'%'.$key.'%'
                                                )
                                                
                                                 ),'limit'=>12
                                                );
                $products=$this->Paginator->paginate('Product');
            
            }
        }
        $this->set(compact('products'));
            
    }
    public function checkProductCode($product_code,$id=null)
    {
       $this->autoRender=false;
       $this->layout=false;
       $product = $this->Product->find('all',array('conditions'=>array('Product.product_code'=>$product_code,'Product.id !='=>$id)));
       if(!empty($product))
       {
           return "notOK";
       }
       else return "OK";
       
    }
    public function types($type)
    {
        $order = array('Product.price'=>'DESC');
        $idOrder=1;
        if(isset($_POST['order']))
        {
            $idOrder=$_POST['order'];
            if($idOrder==2)
            {
                $order = array('Product.price'=>'ASC');
            }
        }
        if($type==1)
        {
            $title_for_layout="Top sản phẩm mới";
            
          
        }
        else if($type==2){
            $title_for_layout="Sản phẩm hot";
        }
        else{
            $type=0;
            $title_for_layout="Sản phẩm thông thường";
        }
        $this->Paginator->settings=array(
            'conditions'=>array('Product.type'=>$type),
            'order'=> $order,
            'limit'=>8,
            
            'recursive'=>-1
            );
        $products=$this->Paginator->paginate('Product');
        $this->set(compact('type','products','idOrder','title_for_layout'));

    }        
            
            

}
